<template>
  <el-dialog v-model="isShow" align-center draggable title="创建" width="60%">
    <div class="ml-20 my-3 flex justify-start">
      <el-form-item label="所属角色">
        <el-tree-select v-model="selectRoleIds" :data="roleTreeData" :render-after-expand="false" multiple />
      </el-form-item>
    </div>
    <FormCreate v-model:api="fApi" :option="options" :rule="formRules" @submit="submitData"></FormCreate>

    <div class="flex justify-end">
      <el-button type="primary" @click="submitData">提交</el-button>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, nextTick, onMounted, onUnmounted, reactive } from "vue";
import formCreate from "@form-create/element-ui";
import { GetCreateFormRule } from "../columns/resetCreate";
import { SysUser } from "../columns/data";
import { formGlobalOption } from "@/components/FormCreate/global";
import { requestSysUserCreate } from "@/api/modules/sysUser";
import { dtoSysUserCreate } from "@/api/dbdto/dtoSysUser";
import { ResultData } from "@/api/interface";
import { RespOk } from "@/constant/codes";
import { ElMessage } from "element-plus";
import CreateColumnsData = SysUser.CreateColumnsData;
import { GetUpdateFormRule } from "@/views/system/sysUser/columns/resetUpdate";
import { requestGetRoleTreeSelect } from "@/api/modules/sysRole";
import { TreeSelect } from "@/api/interface/Common/TreeSelect";

let emits = defineEmits(["reload"]);
const selectRoleIds = ref([]);
const roleTreeData = ref<TreeSelect[]>([] as Array<TreeSelect>);
onMounted(() => {
  requestGetRoleTreeSelect().then((res: ResultData) => {
    if (res.code == RespOk) {
      roleTreeData.value = res.data as Array<TreeSelect>;
    }
  });
});

//form-create 相关
let FormCreate = formCreate.$form(); //获取 formCreate 组件
const fApi = ref(); //文档：http://www.form-create.com/v3/instance.html
let options: any = formGlobalOption;
let formRules = ref(GetCreateFormRule(CreateColumnsData));

//提交按钮点击事件
const submitData = () => {
  if (selectRoleIds.value.length == 0) {
    ElMessage({ type: "error", message: "请选择用户所属角色" });
    return;
  }
  let formData: dtoSysUserCreate = fApi.value.formData(); //获取表单数据
  formData.role_ids = selectRoleIds.value.join(",");
  fApi.value.validate((valid: any) => {
    if (valid === true || valid.length <= 0) {
      requestSysUserCreate(formData).then((res: ResultData<any>) => {
        if (res.code == RespOk) {
          ElMessage({ type: "success", message: "创建成功" });
          isShow.value = false;
          emits("reload");
        }
      });
    } else {
      ElMessage({ type: "error", message: "表单校验不通过" });
    }
  });
};

//以下是弹窗控制相关api
let isShow = ref(false);
const ShowPop = () => {
  isShow.value = true;
  nextTick(() => {
    //fApi.value.xxx  //这里操作fapi
    //fApi.value.Se
  });
};
defineExpose({ ShowPop });
</script>

<style lang="scss" scoped></style>
